<?php

include_once('../../index.php');
include_once('templates/core/Smarty.class.php');

$isCookied = isset($_COOKIE['identify'], $_COOKIE['hash']);
$isReceiveForm = count($_POST) > 0;

$isIdentify = false;
$message = '';

if (isset($_GET['update']) && $_GET['update'] == '0') {
  $message = '';
}

if (isset($_GET['update']) && $_GET['update'] == '1') {
  $message = 'Modificación exitosa';
}

if (isset($_GET['update']) && $_GET['update'] == '2') {
  $message = 'Contraseña no modificada';
}

if (isset($_GET['update']) && $_GET['update'] == '3') {
  $message = 'No se hicieron modificaciones';
}

$id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';

if ($isCookied) {
  //index properties
  $post = new Post($db);
  $post->identify = $_COOKIE['identify'];
  $post->hash = $_COOKIE['hash'];
  $isIdentify = $post->identify();
}

//Is not identify user
if (!$isIdentify) {
  // return to login
  header('Location: users.php?page=login');
  return;
}

//Is superuser needed
if ($isIdentify) {
  //SUPERUSER PROCESS
  $isSuperUser = $post->is_super_user();
}

if (!$isSuperUser) {
  header('Location: /');
  return;
}

if ($isReceiveForm) {
  $isUpdate = false;

  $post = new Post($db);
  $post->id = $id;
  $post->identify = $_COOKIE['identify'];
  $post->hash = $_COOKIE['hash'];


  if (isset($_POST['rol'])) {
    $post->rol = $_POST['rol'];
    $isUpdate = $post->update_rol();

    if (!$isUpdate) {
      header("Location: users.php?page=update&id={$id}&update=3");
    }

    if ($isUpdate) {
      header("Location: users.php?page=update&id={$id}&update=1");
    }
  }

  if (isset($_POST['softDelete'])) {
    $post->softDelete = $_POST['softDelete'];
    $isUpdate = $post->update_softDelete();

    if (!$isUpdate) {
      header("Location: users.php?page=update&id={$id}&update=3");
    }

    if ($isUpdate) {
      header("Location: users.php?page=update&id={$id}&update=1");
    }
  }

  if (isset($_POST['password']) && $_POST['password'] != '') {
    $post->password = hash('sha512', $_POST['password']);
    $isUpdate = $post->update_password();

    if (!$isUpdate) {
      header("Location: users.php?page=update&id={$id}&update=2");
    }

    if ($isUpdate) {
      header("Location: users.php?page=update&id={$id}&update=1");
    }
  }

}

//index properties
$post = new Post($db);
$post->id = $id;
//read single user
$post->read_single();

$post_arr = array(
  'rol' => $post->rol,
  'name' => $post->name,
  'softDelete' => $post->softDelete,
);

if($post_arr) {
  //DECLARE FORM VARIABLES
  $smarty = new smarty();
  $smarty->assign('id', $id);
  $smarty->assign('name', $post->name);
  $smarty->assign('rol', $post->rol);
  $smarty->assign('softDelete', $post->softDelete);
  $smarty->assign('password', '');
  $smarty->assign('message', $message);
  $smarty->display("templates/{$_REQUEST['page']}.tpl");
}
else {
  header('Location: users.php?page=read');
}

?>